package com.typingtutor.ui.compose;

import com.typingtutor.dto.RandomRuleDAO;
import com.typingtutor.util.MappingDatabaseTableUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * ComboBoxFieldPanel 表示单个下拉框组件，
 * 包含一个 JLabel（显示名称）、一个 JComboBox 及一个删除按钮（可选），
 * 同时支持右键删除（如果允许删除）。
 */
public class ComboBoxFieldPanel extends JPanel {
    private JComboBox<String> comboBox;
    private final JPanel contentPanel;

    public ComboBoxFieldPanel(String uuid, JPanel contentPanel, String fieldName, String[] options, boolean canDelete) {
        this.contentPanel = contentPanel;
        setLayout(new GridBagLayout()); // 使用 GridBagLayout 实现对齐
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(2, 2, 2, 2); // 统一组件间距

        // ---------------------- JLabel 标签列 ----------------------
        gbc.gridx = 0;    // 第1列
        gbc.gridy = 0;    // 第1行
        gbc.anchor = GridBagConstraints.LINE_END; // 标签右对齐
        gbc.weightx = 0; // 标签列不扩展
        JLabel label = new JLabel(fieldName + ": ");
        label.setPreferredSize(new Dimension(120, 25)); // 固定标签宽度
        add(label, gbc);

        // ---------------------- JComboBox 下拉框列 ----------------------
        gbc.gridx = 1;    // 第2列
        gbc.fill = GridBagConstraints.HORIZONTAL; // 下拉框水平扩展
        gbc.weightx = 1.0; // 占据剩余水平空间
        comboBox = new JComboBox<>(options);
        comboBox.setPreferredSize(new Dimension(300, 25));
        comboBox.setEditable(false);
        add(comboBox, gbc);
        comboBox.addItemListener(e -> {
            // 检查事件状态是否为选中状态
            if (e.getStateChange() == ItemEvent.SELECTED) {
                // 获取选中的项
                String selectedItem = (String) e.getItem();
                RandomRuleDAO.getInstance().updateRandomRuleById(uuid,
                        MappingDatabaseTableUtils.getTableField(fieldName), selectedItem);
            }
        });
        if (canDelete) {
            // 删除按钮：紧凑图标按钮
            JButton deleteButton = new JButton("删除");
            deleteButton.addActionListener(e -> removeThis());
            gbc.gridx = 2;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.LINE_START; // 左对齐
            gbc.weightx = 0.0; // 不拉伸
            add(deleteButton, gbc);

            // 右键删除
            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    if (e.isPopupTrigger()) {
                        removeThis();
                    }
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    if (e.isPopupTrigger()) {
                        removeThis();
                    }
                }
            });
        }
    }

    private void removeThis() {
        Component[] components = contentPanel.getComponents();
        int index = -1;
        for (int i = 0; i < components.length; i++) {
            if (components[i] == this) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            contentPanel.remove(index);
            // 移除对应的垂直间隔
            if (index + 1 < contentPanel.getComponentCount() && contentPanel.getComponent(index + 1) instanceof Box.Filler) {
                contentPanel.remove(index + 1);
            }
            contentPanel.revalidate();
            contentPanel.repaint();
        }
    }

    public String getComboBoxValue() {
        return (String) comboBox.getSelectedItem();
    }

    public void setComboBoxValue(String value) {
        comboBox.setSelectedItem(value);
    }

    // 添加获取选中值的方法
    public String getSelectedValue() {
        return (String) comboBox.getSelectedItem();
    }
    public void setSelectValue(String text) {
        comboBox.setSelectedItem(text);
    }
}
